package com.neu.question.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neu.question.common.utils.DateUtil;
import com.neu.question.common.utils.SMSUtils;
import com.neu.question.common.utils.UUIDUtil;
import com.neu.question.common.utils.ValidateCodeUtils;
import com.neu.question.domain.PasswordQuestion;
import com.neu.question.domain.ProjectInfo;
import com.neu.question.domain.UserInfo;
import com.neu.question.domain.*;
import com.neu.question.mapper.ProjectInfoMapper;
import com.neu.question.mapper.RespondentInfoMapper;
import com.neu.question.mapper.TenantsPropertyInfoMapper;
import com.neu.question.mapper.UserInfoMapper;
import com.neu.question.service.EndUserInfoService;
import com.neu.question.service.RespondentInfoService;
import com.neu.question.service.TenantsPropertyInfoService;
import com.neu.question.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DELL
 * @description 针对表【user_info】的数据库操作Service实现
 * @createDate 2022-10-31 19:09:11
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Autowired
    private UserInfoMapper userEntityMapper;

    @Autowired
    private ProjectInfoMapper projectEntityMapper;

    @Autowired
    private TenantsPropertyInfoMapper tenantsPropertyInfoMapper;
    public boolean userMIBAOCheck(Map<String, String> map){
        String user = map.get("username");
        String answer1 = map.get("answer1");
        String answer2 = map.get("answer2");
        String question2=map.get("question2");
        String question1=map.get("question1");

        String s = userEntityMapper.getUserMIBAO(user);
        //将json字符串转换为json对象
        if(s==null){
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(s);
        Map<String,String> map1 = jsonObject.getObject("question", Map.class);
        //获取json对象中的密保问题
        String answer_1 = map1.get("answer1");
        String answer_2 = map1.get("answer2");
        String question_1 = map1.get("question1");
        String question_2 = map1.get("question2");
        if(answer_1.equals(answer1)&&answer_2.equals(answer2)&&
                question_1.equals(question1)&&question_2.equals(question2)){
                return true;
        }else {
            return false;
        }
    }

    /**
     * 根据电话或用户名设置用户的密保问题
     * @param map
     * @return
     */
    @Override
    public boolean insertQuestion(Map<String, String> map) {
        PasswordQuestion passwordQuestion = new PasswordQuestion();

        String user=map.get("user");

        passwordQuestion.setQuestion(map);
        //将密保问题转换为json格式存储
        String questionJson = JSONObject.toJSONString(passwordQuestion);
        return userEntityMapper.insertQuestion(user, questionJson);
    }

    @Autowired
    private EndUserInfoService endUserInfoService;

    @Autowired
    private RespondentInfoService respondentInfoService;

    private TenantsPropertyInfoService tenantsPropertyInfoService;

    @Override
    /**
     * 根据电话查询用户信息
     *
     * @param userEntity
     * @return
     */
    public List<UserInfo> getUserByPhone(UserInfo userEntity) {
        List<UserInfo> result = userEntityMapper.getUserByPhone(userEntity);
        return result;
    }

    @Override
    public List<UserInfo> selectUserInfo(UserInfo userEntity) {
        List<UserInfo> result = userEntityMapper.selectUserInfo(userEntity);
        return result;
    }

    @Override
    public PageInfo queryUserList(Map<String, Object> map) {
        //分页设置
        PageHelper.startPage((Integer) map.get("pageNum"), (Integer) map.get("pageSize"));
        List<Map<String, Object>> mapList = userEntityMapper.queryUserInfoByRole(map);
        PageInfo<Map<String, Object>> objectPageInfo = new PageInfo<>(mapList);
        return objectPageInfo;
    }

    @Override
    /**
     * 创建用户的基本信息
     *
     * @param map
     * @return
     */
    public int addUserInfo(Map<String, Object> map) {
        if (map.get("username") != null) {
            int userResult = userEntityMapper.queryExistUser(map);
            if (userResult != 0) {
                //用户名已经存在
                return 3;
            }
        }
        if (map.get("phoneNum") != null) {
            int PhoneResult = userEntityMapper.queryExistPhone(map);
            if (PhoneResult != 0) {
                return 4;
            }
        }
        String id = UUIDUtil.getOneUUID();
        map.put("id", id);
        //创建时间
        Date date = DateUtil.getCreateTime();
        map.put("creationDate", date);
        map.put("lastUpdateDate", date);
        //创建人
        //String createduserid = map.get("id").toString();
        //Map<String,Object> querymap = new JSONObject();
        //querymap.put("id",createduserid);
        // Map<String,Object> queryresult = userEntityMapper.queryUserById(querymap);
        //String user = queryresult.get("username").toString();
        String user = map.get("opusername").toString();

        map.put("createdBy", user);
        map.put("lastUpdatedBy", user);
        //前台传入的时间戳转换
        String startTimeStr = map.get("startTime").toString();
        String endTimeStr = map.get("stopTime").toString();
        Date startTime = DateUtil.getMyTime(startTimeStr);
        Date endTime = DateUtil.getMyTime(endTimeStr);
        map.put("startTime", startTime);
        map.put("stopTime", endTime);

        int result = userEntityMapper.addUserInfo(map);
        //根据角色类型，在关联表中加入数据
        //若为租户
        if (map.get("roleId").toString().equals("1")) {
            Map<String, Object> tenantsmap = new JSONObject();
            tenantsmap.put("userId", id);
            tenantsmap.put("property", "0.00");
            tenantsmap.put("projectNum", "0");
            tenantsmap.put("questionnaireNum", "0");
            tenantsmap.put("answerNum", "0");
            tenantsmap.put("projectRemaining", "0");
            tenantsmap.put("questionnaireRemaining", "0");
            tenantsmap.put("answerRemaining", "0");
            tenantsmap.put("status", "1");
            tenantsmap.put("id", UUIDUtil.getOneUUID());
            tenantsPropertyInfoMapper.addTenantsPropertyInfo(tenantsmap);
        } else if (map.get("roleId").toString().equals("2")) {
            //若为用户
            //租户才能创建用户
            if (map.get("username") == null) {
                //没有传入租户ID
                //成功存入user_info  但是没有成功存入end_user_info
                return 2;
            }
            EndUserInfo endUserInfo = new EndUserInfo();
            endUserInfo.setUserId(id);
            endUserInfo.setTenantsId(map.get("tenantsId").toString());
            endUserInfo.setQuestionnaireNum(map.get("questionnaireNum").toString());

            if (endUserInfoService.save(endUserInfo)) {
                //如果成功存入不操作
                return result;
            } else {
                //成功存入user_info  但是没有成功存入end_user_info
                return 5;
            }
//            endUserInfoService.save();
        } else if (map.get("roleId").toString().equals("3")){
            //如果为答者
            RespondentInfo respondentInfo = new RespondentInfo();
            respondentInfo.setUserId(id);
            respondentInfo.setEmail(map.get("email").toString());
            if (respondentInfoService.save(respondentInfo)) {
                //如果成功 不操作
                return result;
            } else {
                //成功存入User_info  但是没有成功存入 respondent_info
                return 6;
            }
        }
        return result;
    }

    @Override
    /**
     * 编辑用户的基本信息
     *
     * @param map
     * @return
     */
    public int modifyUserInfo(Map<String, Object> map) {
        if (map.get("username") != null) {
            int userResult = userEntityMapper.queryExistUser(map);
            if (userResult != 0) {
                //用户名已经存在
                return 3;
            }
        }
        //根据用户id判断是否存在项目
        ProjectInfo projectEntity = new ProjectInfo();
        projectEntity.setUserId(map.get("id").toString());
        int k = projectEntityMapper.queryExistProjectByUser(projectEntity);
        if (k != 0) {
            //存在项目
            return 4;
        }
        //创建时间
        Date date = DateUtil.getCreateTime();
        map.put("lastUpdateDate", date);
        //编辑人
        String user = map.get("opusername").toString();
        map.put("lastUpdatedBy", user);
        //前台传入的时间戳转换
        String startTimeStr = map.get("startTime").toString();
        String endTimeStr = map.get("stopTime").toString();
        Date startTime = DateUtil.getMyTime(startTimeStr);
        Date endTime = DateUtil.getMyTime(endTimeStr);
        map.put("startTime", startTime);
        map.put("stopTime", endTime);

        int result = userEntityMapper.modifyUserInfo(map);
        return result;


    }


    /**
     * 新 编辑用户的信息 改
     */
    @Override
    public int allModifyUserInfo(Map<String, Object> map) {
        //首先判断用户类型

            //如果为管理员
            if (map.get("username") != null) {
                int userResult = userEntityMapper.queryExistUser(map);
                if (userResult != 0) {
                    //用户名已经存在
                    return 3;
                }
            }
            //根据用户id判断是否存在项目
            ProjectInfo projectEntity = new ProjectInfo();
            projectEntity.setUserId(map.get("id").toString());
            int k = projectEntityMapper.queryExistProjectByUser(projectEntity);
            if (k != 0) {
                //存在项目
                return 4;
            }
            //创建时间
            Date date = DateUtil.getCreateTime();
            map.put("lastUpdateDate", date);
            //编辑人
            String user = map.get("opusername").toString();
            map.put("lastUpdatedBy", user);
            //前台传入的时间戳转换
            String startTimeStr = map.get("startTime").toString();
            String endTimeStr = map.get("stopTime").toString();
            Date startTime = DateUtil.getMyTime(startTimeStr);
            Date endTime = DateUtil.getMyTime(endTimeStr);
            map.put("startTime", startTime);
            map.put("stopTime", endTime);

            int result = userEntityMapper.modifyUserInfo(map);
            //判断用户类型
        if (map.get("roleId").toString().equals("0")) {
            //如果为管理员
            return result;
        } else if (map.get("roleId").toString().equals("1")) {
            //如果为租户 则需要对租户的详细信息也进行修改
            QueryWrapper<TenantsPropertyInfo> tenantsPropertyInfoQueryWrapper = new QueryWrapper<>();
            tenantsPropertyInfoQueryWrapper.eq("user_id", map.get("id").toString());
            TenantsPropertyInfo te = tenantsPropertyInfoService.getOne(tenantsPropertyInfoQueryWrapper);
            te.setProperty(map.get("property").toString());
            te.setProjectNum(map.get("projectNum").toString());
            te.setQuestionnaireNum(map.get("questionnaireNum").toString());
            te.setAnswerNum(map.get("answerNum").toString());
            te.setProjectRemaining(map.get("projectRemaining").toString());
            te.setQuestionnaireRemaining(map.get("questionnaireRemaining").toString());
            te.setAnswerRemaining(map.get("answerRemaining").toString());
            te.setGroupNum(map.get("groupNum").toString());
            te.setGroupRemaining(map.get("groupRemaining").toString());
            if (tenantsPropertyInfoService.save(te)) {
                return result;
            }else {
                //修改租户详细信息失败
                return 5;
            }
        } else if (map.get("roleId").toString().equals("2")) {
            //如果为用户
            QueryWrapper<EndUserInfo> endUserInfoQueryWrapper = new QueryWrapper<>();
            endUserInfoQueryWrapper.eq("user_id", map.get("id").toString());
            EndUserInfo ed = endUserInfoService.getOne(endUserInfoQueryWrapper);
            ed.setTenantsId(map.get("tenantsId").toString());
            ed.setQuestionnaireNum(map.get("questionnaireNum").toString());
            ed.setUseProject(map.get("useProject").toString());
            ed.setUseQuestionnaire(map.get("useQuestionnaire").toString());
            ed.setUseGroup(map.get("useGroup").toString());
            ed.setUseAnswer(map.get("useAnswer").toString());
            if (endUserInfoService.save(ed)) {
                return result;
            } else {
                //修改用户详细信息失败
                return 6;
            }

        } else if (map.get("roleId").toString().equals("3")) {
            //如果为答者
            QueryWrapper<RespondentInfo> respondentInfoQueryWrapper = new QueryWrapper<>();
            respondentInfoQueryWrapper.eq("user_id", map.get("id").toString());
            RespondentInfo ed = respondentInfoService.getOne(respondentInfoQueryWrapper);
            ed.setGroupId(map.get("groupId").toString());
            ed.setEmail(map.get("email").toString());
            ed.setQuestionnaireId(map.get("questionnaireId").toString());
            if (respondentInfoService.save(ed)) {
                return result;
            } else {
                //修改答者详细信息失败
                return 7;
            }
        }


        return result;

    }


    @Override
    public Map<String, Object> selectUserInfoById(UserInfo userEntity) {
        Map<String, Object> result = userEntityMapper.selectUserInfoById(userEntity);
        return result;
    }

    @Override
    public int modifyUserStatus(Map<String, Object> map) {
        String id = (String) map.get("id");
        int curstatus = Integer.parseInt(userEntityMapper.queryUserStatus(id));
        Map<String, Object> map1 = new JSONObject();
        map1.put("id", id);
        if (curstatus == 1) {
            int nextstatus = 0;
            map1.put("status", nextstatus);
        } else {
            int nextstatus = 1;
            map1.put("status", nextstatus);
        }
        userEntityMapper.modifyUserStatus(map1);
        return 1;
    }

    @Override
    public int modifyUserpassword(Map<String, Object> map) {
        String password = (String) map.get("password");
        String phn = (String) map.get("phoneNum");
        Map<String, Object> map1 = new JSONObject();
        map1.put("password", password);
        map1.put("phoneNum", phn);
        int result = userEntityMapper.modifyUserpassword(map1);
        //userEntityMapper.modifyUserStatus(map1);
        return 1;
    }

    @Override
    public int deteleUserInfoById(UserInfo userEntity) {
        //根据用户id判断是否存在项目
        ProjectInfo projectEntity = new ProjectInfo();
        projectEntity.setUserId(userEntity.getId());
        int k = projectEntityMapper.queryExistProjectByUser(projectEntity);
        if (k != 0) {
            //存在项目
            return 4;
        }
        //判断用户类型
        if (userEntity.getRoleId().equals("1")) {
            //如果是租户 则需要删除租户的详细信息
            tenantsPropertyInfoMapper.deleteTenantsPropertyInfo(userEntity.getId());

        } else if (userEntity.getRoleId().equals("2")) {
            //如果是用户
            QueryWrapper<EndUserInfo> qw = new QueryWrapper<>();
            qw.eq("user_id", userEntity.getId());
            if (!endUserInfoService.remove(qw)) {
                return 5;
            }

        } else if (userEntity.getRoleId().equals("3")) {
            //如果是答者
            QueryWrapper<RespondentInfo> qw = new QueryWrapper<>();
            qw.eq("user_id", userEntity.getId());
            if (!respondentInfoService.remove(qw)) {
                return 6;
            }
        } else {
            if (!(userEntityMapper.deteleUserInfoById(userEntity) == 1)){
                return 3;
            }
        }
        return 0;
    }

    @Override
    public int selectUserByPhone(Map<String, Object> map) {
        int result = userEntityMapper.selectUserByPhone(map);
        if (result == 0) {
            //不存在
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    /**
     * 发送验证码
     */
    public String sendCode(Map<String, Object> map) {
        String phone = map.get("phoneNum").toString();
        String code = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
        //储存验证码
        try {
            SMSUtils.sendMessage(phone, code, SMSUtils.TEMPLATE_RESET_ID);
            return code;
        } catch (Exception e) {
            return "0";
        }
    }

    @Override
    /**
     * 验证码验证
     */
    public int checkCode(Map<String, Object> map) {
        String code = map.get("code").toString();
        String code_valid = map.get("code_valid").toString();
        //储存验证码
        if (code.equals(code_valid)) {
            return 1;
        } else {
            return 0;
        }
    }

}




